import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("输入缓冲区大小：");
        int i = scanner.nextInt();
        Clerk clerk = new Clerk(i);

        System.out.print("生产者生产速度：");
        i = scanner.nextInt();
        Producer p1 = new Producer(clerk,i);
        Producer p2 = new Producer(clerk,i);
        System.out.print("消费者消费速度：");
        i = scanner.nextInt();
        Consumer c1 = new Consumer(clerk,i);

        p1.setName("生产者1");
        p2.setName("生产者2");
        c1.setName("消费者1");

        p1.start();
        p2.start();
        c1.start();
    }

}

class Clerk {  // 店员
    private int productNum = 0; // 现有产品数量
    private int size; // 缓冲区大小

    Clerk(int i){
        this.size = i;
    }


    public synchronized void add(int i){ // 店员放入产品

        if(productNum >= size){
            System.out.println("缓冲区满了，生产者等待");
            try {
                wait(); // 等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            productNum += i;
            System.out.println(Thread.currentThread().getName() + "生产了，现有 " + productNum + " 个产品");

            notifyAll(); // 生成了就叫消费者来
        }

    }

    public synchronized void min(int i){ // 店员取出产品

        if(productNum <= 0){
            try {
                System.out.println("缓冲区空了，消费者等待");
                wait(); // 等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            productNum -= i;
            System.out.println(Thread.currentThread().getName() + "消费了，现有 " + productNum + " 个产品");

            notifyAll(); // 消费了就叫生产者生成
        }
    }
}

class Producer extends Thread { // 生产者
    private Clerk clerk;

    private int time; // 生产的速度

    public Producer(Clerk clerk,int t){
        this.clerk = clerk;
        this.time = t;
    }

    @Override
    public void run() {

        while (true){
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("生产者开始生产咯");
            clerk.add(1); // 每次生产的数量
        }

    }

}

class Consumer extends Thread { // 消费者
    private Clerk clerk;

    private int time; // 生产的速度

    public Consumer(Clerk clerk,int t){
        this.clerk = clerk;
        this.time = t;
    }

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("消费者来买东西咯");
            clerk.min(1); // 每次消费的数量
        }
    }
}